package com.shanzmoo.admin.web;

import com.alibaba.fastjson.JSON;
import com.shanzmoo.admin.domain.AuthUser;
import com.shanzmoo.base.bean.SHttpResponse;
import com.shanzmoo.base.constant.Constant;
import com.shanzmoo.core.manager.JwtManager;
import com.shanzmoo.core.auth.LoginReq;
import com.shanzmoo.core.auth.vo.AuthUserVo;
import com.shanzmoo.admin.manager.SysUserManager;
import com.shanzmoo.db.sys.entity.OutletInfoEntity;
import com.shanzmoo.db.sys.entity.UserEntity;
import com.shanzmoo.db.sys.service.IOutletInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

@Slf4j
@Api(tags = "权限-登录")
@RestController
@RequestMapping("/api/auth")
public class LoginController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtManager jwtManager;

    @Autowired
    private SysUserManager sysUserManager;

    @Autowired
    private IOutletInfoService outletInfoService;

    @ApiOperation(value = "登录")
    @PostMapping("/login")
    public SHttpResponse<AuthUserVo> login(@Valid @RequestBody LoginReq loginReq) {
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(loginReq.getUsername(), loginReq.getPassword()));

        SecurityContextHolder.getContext().setAuthentication(authentication);

        AuthUser authUser = JSON.parseObject(JSON.toJSONString(authentication.getPrincipal()), AuthUser.class);

        String jwt = jwtManager.createJWT(false, authUser.getUserId(), authUser.getUsername(),
                authUser.getRoleIds(), authUser.getAuthorities());

        UserEntity user = sysUserManager.getUserByName(loginReq.getUsername());

        AuthUserVo userVo = new AuthUserVo();
        userVo.setUserId(user.getUserId());
        userVo.setUsername(user.getUsername());
        userVo.setOutletId(user.getOutletId());
        if (0 == user.getOutletId()) {
            userVo.setOutletName("系统管理员");
            userVo.setIndex("/index/home");
        } else {
            OutletInfoEntity outletInfo = outletInfoService.getById(user.getOutletId());
            userVo.setOutletName(outletInfo.getName());

            if (1 == outletInfo.getId()) {
                userVo.setIndex("/order/mall/self");
            } else {
                userVo.setIndex("/order/outlet/list");
            }
        }
        userVo.setToken(jwt);

        return SHttpResponse.ok(userVo);
    }


    @ApiOperation(value = "退出")
    @PostMapping("/logout")
    public SHttpResponse<Boolean> logout() {
        try {
            // 从redis中删除jwt信息
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                    .getRequestAttributes()).getRequest();
            jwtManager.invalidateJWT(request);
        } catch (SecurityException e) {
            return SHttpResponse.fail(Constant.ERRCODE_LOGIC, "退出异常");
        }
        return SHttpResponse.ok();
    }
}
